﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.ComponentModel;

namespace MoneyWentWhere.DataModel.Binding
{
    public class CategorySet : IEnumerable<String>
    {
        public const string Separator = "/";

        HashSet<String> _set = new HashSet<string>();

        public CategorySet()
        {
            Add(""); // Always add an empty category
        }

        public bool Add(String category)
        {
            if (category == null) { return false; }

            // Treat "/foo" as "foo"
            if (category.StartsWith(Separator))
            {
                category = category.Substring(Separator.Length);
            }

            bool added = _set.Add(category);
            if (!added) { return false; }

            // Add parents recursively
            while (true)
            {
                category = GetParent(category);
                if (category == null) { break; }
                Add(category);                
            }
            return true;
        }

        /// <summary>
        /// Get parent category, null if no parent exists.
        /// </summary>
        /// <param name="category"></param>
        /// <returns></returns>
        public String GetParent(String category)
        {
            int index = category.LastIndexOf(Separator);
            if (index < 0) { return null; }
            return category.Substring(0, index);
        }

        #region IEnumerable<string> Members

        IEnumerator<string> IEnumerable<string>.GetEnumerator()
        {
            return _set.GetEnumerator();
        }

        System.Collections.IEnumerator System.Collections.IEnumerable.GetEnumerator()
        {
            return _set.GetEnumerator();
        }

        #endregion
    }
}
